﻿using System;
using System.ComponentModel;
using System.IO;
using TfsComLib.TfsBranchLib2;
using WpfAdvControls.Plate;

namespace TfsBranchLib2.Model
{
    public class RecentBranchSets : IRecentBranchSets, INotifyPropertyChanged
    {
        private BranchSetPrecedentContainer currentContainer;
        private readonly string FileName = "data.xml";

        private bool isLoaded;

        private readonly MTObservableCollection<BranchSetItem> items = new MTObservableCollection<BranchSetItem>();

        private readonly string SerializationDir;
        private readonly BranchSetContainerStorage storage;

        public RecentBranchSets()
        {
            storage = new BranchSetContainerStorage();
            storage.OnLoad += storage_OnLoad;
            storage.OnSave += storage_OnSave;
            SerializationDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                "BranchedHistoryPlugin", "v2");
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void LoadForTrunk(string rootBranch)
        {
            if (!isLoaded)
            {
                storage.Load();
                isLoaded = true;
            }
            currentContainer = storage.GetContainer(rootBranch);
            UpdateBranchSetList();
        }

        public void ApplyPrecedent(BranchSet branchSet)
        {
            if (currentContainer == null)
            {
                // Do nothing if trunk (serializing context) is not defined
                return;
            }
            currentContainer.AddPrecedent(branchSet);
            storage.Save();
            UpdateBranchSetList();
        }

        public void UpdateBranchSetList()
        {
            items.Clear();
            //items.Add(BranchSetItem.AllBranchesItem);
            foreach (var branchSetAggr in currentContainer.Elements)
            {
                items.Add(new BranchSetItem {BranchSetValue = branchSetAggr, ItemType = BranchSetItemType.Standard});
            }

            NotifyPropertyChange("Items");
        }

        public MTObservableCollection<BranchSetItem> Items
        {
            get { return items; }
            set { }
        }

        private void storage_OnSave(object sender, BranchSetContainerStorage.XmlSerializationEventArgs e)
        {
            try
            {
                if (!Directory.Exists(SerializationDir))
                {
                    Directory.CreateDirectory(SerializationDir);
                }
                using (TextWriter tw = new StreamWriter(Path.Combine(SerializationDir, FileName)))
                {
                    tw.Write(e.SerializedData);
                }
            }
            catch
            {
            }
        }

        private void storage_OnLoad(object sender, BranchSetContainerStorage.XmlSerializationEventArgs e)
        {
            try
            {
                var serFile = Path.Combine(SerializationDir, FileName);
                if (!File.Exists(serFile)) return;
                using (TextReader tr = new StreamReader(Path.Combine(SerializationDir, FileName)))
                {
                    e.SerializedData = tr.ReadToEnd();
                }
            }
            catch
            {
            }
        }

        private void NotifyPropertyChange(string property)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(property));
            }
        }
    }
}